package com.tool_stdy.thread;

import java.util.concurrent.*;

/**
 * Created by yan_li on 2017/2/8.
 */
public class FutureTaskTest {

    final ConcurrentMap<Object, Future<String>> taskCache = new ConcurrentHashMap<Object, Future<String>>();

    public String executeTask(final String taskName) throws ExecutionException, InterruptedException {
        while (true) {
            Future<String> future = taskCache.get(taskName);
            if (future == null) {
                Callable<String> task = new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        System.out.println("["+System.currentTimeMillis()+"]"+Thread.currentThread().getName()+"---->"+taskName);
                        Thread.sleep(100);
                        return taskName;
                    }
                };
                FutureTask<String> futureTask = new FutureTask<String>(task);
                future = taskCache.putIfAbsent(taskName, futureTask);
                if (future == null) {
                    future = futureTask;
                    System.out.println(Thread.currentThread().getName()+"--Enter");
                    futureTask.run();
                }
            }
            System.out.println(Thread.currentThread().getName()+"--Out");
            return future.get();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final FutureTaskTest test = new FutureTaskTest();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    test.executeTask("aa");
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
//
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    test.executeTask("aa");
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        Thread.sleep(10000);
    }
}
